﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TemplatesPrint.DBHelper;
using TemplatesPrint.EntityHandle;
using TemplatesPrint.Entitys;
using TemplatesPrint.MySqlEntitys;

namespace TemplatesPrint.Tools
{
    public class AutoUpLoad
    {
        public static void DataUpLoad()
        {
            string ip = PublicTool.IpAddress;
            Thread upThread = new Thread(DataUpThread);
            upThread.IsBackground = true;
            upThread.Start();
        }

        static void DataUpThread()
        {
            while (true)
            {
                Thread.Sleep(10000);
                try
                {
                    if (PublicTool.GetTemplatesType.ToLower() != "LocalFile".ToLower())
                    {
                        UpTask();
                        UpCode();
                        UpLog();
                    }
                    DeleteHistory();
                }
                catch (Exception ex)
                {
                    TaskLogHandle.SaveLog("", "系统异常：数据上传", ex.ToString(), "false");
                }
            }
        }

        static void UpTask()
        {
            using (var db = SQLiteHelper.GetInstance())
            {
                var tasks = db.Queryable<TaskInfoEntity>().ToList();

                var hisTasks = db.Queryable<TaskInfoHistoryEntity>()
                      .Where(x => x.IsUpLoad == null || x.IsUpLoad == "0")
                      .OrderBy(x => x.CreateTime)
                      .Take(100)
                      .ToList();

                if (tasks.Count > 0 || hisTasks.Count > 0)
                {
                    List<dynamic> uploads = new List<dynamic>();
                    var upTasks = new List<Fr_TaskInfoEntity>();
                    foreach (var task in tasks)
                    {
                        var tmp = new
                        {
                            taskId = task.Id.ToString(),
                            source = task.Source,
                            type = task.Type,
                            templateInfo = task.TemplateInfo,
                            printerInfo = task.PrinterInfo,
                            data = task.Data,
                            printCopies = task.Printcopies,
                            startTime = string.IsNullOrEmpty(task.StartTime) ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : task.StartTime,
                            endTime = string.IsNullOrEmpty(task.EndTime) ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : task.EndTime,
                            updateTime = task.UpdateTime == null ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : task.UpdateTime,
                            status = task.Status,
                            exInfo = task.ExInfo, 
                            msgId = task.MsgId,
                            sourceIp = IpTools.GetMacAddress()
                        };

                        uploads.Add(tmp);
                    }

                    foreach (var task in hisTasks)
                    {
                        var tmp = new
                        {
                            taskId = task.Id.ToString(),
                            source = task.Source,
                            type = task.Type,
                            templateInfo = task.TemplateInfo,
                            printerInfo = task.PrinterInfo,
                            data = task.Data,
                            printCopies = task.Printcopies,
                            startTime = string.IsNullOrEmpty(task.StartTime) ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : task.StartTime,
                            endTime = string.IsNullOrEmpty(task.EndTime) ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : task.EndTime,
                            updateTime = task.UpdateTime == null ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : task.UpdateTime,
                            status = task.Status,
                            exInfo = task.ExInfo,
                            msgId = task.MsgId,
                            sourceIp = IpTools.GetMacAddress()
                        };

                        uploads.Add(tmp);
                    }
                    if (uploads.Count > 0)
                    {
                        var state = PublicTool.Post($"{ PublicTool.ServerDbIp}/print/v1/open/batch/task-info", JsonConvert.SerializeObject(uploads), out string ret);
                        if (state)
                        {
                            var result = JObject.Parse(ret);
                            if (result["code"] != null && result["code"].ToString() != "0")
                            {
                                state = false;
                                ret = "batch/task-info:接口异常"+result["message"].ToString();
                            }
                        }
                        if (state)
                        {
                            if (tasks.Count > 0)
                            {
                                db.Updateable(tasks)
                               .ReSetValue(it => { it.IsUpLoad = "1"; })
                               .UpdateColumns(it => new { it.IsUpLoad })
                               .ExecuteCommand();
                            }
                            if (hisTasks.Count > 0)
                            {
                                db.Updateable(hisTasks)
                               .ReSetValue(it => { it.IsUpLoad = "1"; })
                               .UpdateColumns(it => new { it.IsUpLoad })
                               .ExecuteCommand();
                            }
                        }
                        else
                        {
                            TaskLogHandle.SaveLog("", "上传任务：异常", ret, "false", "上传");
                        }
                    }
                }
            };
        }

        static void UpCode()
        {
            using (var db = SQLiteHelper.GetInstance())
            {
                var codes = db.Queryable<CodeInfoEntity>()
                      .Where(x => x.IsUpLoad == null || x.IsUpLoad == "0")
                      .OrderBy(x => x.CreateTime)
                      .Take(100)
                      .ToList();
                if (codes.Count > 0)
                {
                    List<dynamic> uploads = new List<dynamic>();
                    foreach (var v in codes)
                    {
                        var tmp = new
                        {
                            id = v.Id.ToString(),
                            createTime = DateTime.Parse(v.CreateTime),
                            status = int.Parse(v.Status),
                            barCode = v.Barcode,
                            taskId = v.MsgId,
                            sourceIp = IpTools.GetMacAddress(),
                            codeType = v.Type
                        };

                        uploads.Add(tmp);
                    }
                    if (uploads.Count > 0)
                    {
                        var state = PublicTool.Post($"{ PublicTool.ServerDbIp}/print/v1/open/batch/code-info", JsonConvert.SerializeObject(uploads), out string ret);
                        if (state)
                        {
                            var result = JObject.Parse(ret);
                            if (result["code"] != null && result["code"].ToString() != "0")
                            {
                                state = false;
                                ret = "batch/code-info:接口异常" + result["message"].ToString();
                            }
                        }
                        if (state)
                        {
                            db.Updateable(codes)
                                .ReSetValue(it => { it.IsUpLoad = "1"; })
                                .UpdateColumns(it => new { it.IsUpLoad })
                                .ExecuteCommand();
                        }
                        else
                        {
                            TaskLogHandle.SaveLog("", "上传条码：异常", ret, "false", "上传");
                        }
                    }
                }
            }
        }

        static void UpLog()
        {
            using (var db = SQLiteHelper.GetInstance())
            {
                var logs = db.Queryable<TaskLogEntity>()
                      .Where(x => x.IsUpLoad == null || x.IsUpLoad == "0")
                      .OrderBy(x => x.CreateTime)
                      .Take(100)
                      .ToList();
                if (logs.Count > 0)
                {
                    List<dynamic> uploads = new List<dynamic>();
                    foreach (var v in logs)
                    {
                        var tmp = new
                        {
                            id = v.Id.ToString(),
                            createTime = DateTime.Parse(v.CreateTime),
                            status = string.IsNullOrEmpty(v.Status) ? true : bool.Parse(v.Status),
                            msg = v.Msg,
                            taskId = v.TaskId,
                            sourceIp = IpTools.GetMacAddress(),
                            describe = v.Describe,
                            type = v.Type
                        };

                        uploads.Add(tmp);
                    }
                    if (uploads.Count > 0)
                    {
                        var state = PublicTool.Post($"{ PublicTool.ServerDbIp}/print/v1/open/batch/task-log", JsonConvert.SerializeObject(uploads), out string ret);

                        if (state)
                        {
                            var result = JObject.Parse(ret);
                            if (result["code"] != null && result["code"].ToString() != "0")
                            {
                                state = false;
                                ret = "batch/task-log:接口异常" + result["message"].ToString();
                            }
                        }
                        if (state)
                        {
                            db.Updateable(logs)
                              .ReSetValue(it => { it.IsUpLoad = "1"; })
                              .UpdateColumns(it => new { it.IsUpLoad })
                              .ExecuteCommand();
                        }
                        else
                        {
                            TaskLogHandle.SaveLog("", "上传日志：异常", ret, "false", "上传");
                        }
                    }
                }
            };
        }

        static void DeleteHistory()
        {
            using (var db = SQLiteHelper.GetInstance())
            {
                var date = DateTime.Now.AddDays(-10);
                if (PublicTool.GetTemplatesType.ToLower() != "LocalFile".ToLower())
                {
                    date = DateTime.Now.AddDays(-20);

                    var log = db.Queryable<TaskLogEntity>()
                                .Where(x => DateTime.Parse(x.CreateTime) < date)
                                .First();

                    if (log != null)
                    {
                        db.Deleteable<TaskLogEntity>()
                           .Where(x => DateTime.Parse(x.CreateTime) < date)
                           .ExecuteCommand();

                        db.Deleteable<CodeInfoEntity>()
                           .Where(x => DateTime.Parse(x.CreateTime) < date)
                           .ExecuteCommand();

                        db.Deleteable<TaskInfoHistoryEntity>()
                           .Where(x => DateTime.Parse(x.CreateTime) < date)
                           .ExecuteCommand();
                    }
                }
                else
                {
                    var log = db.Queryable<TaskLogEntity>()
                                .Where(x => DateTime.Parse(x.CreateTime) < date && x.IsUpLoad == "1")
                                .First();

                    if (log != null)
                    {
                        db.Deleteable<TaskLogEntity>()
                       .Where(x => DateTime.Parse(x.CreateTime) < date && x.IsUpLoad == "1")
                       .ExecuteCommand();

                        db.Deleteable<CodeInfoEntity>()
                           .Where(x => DateTime.Parse(x.CreateTime) < date && x.IsUpLoad == "1")
                           .ExecuteCommand();

                        db.Deleteable<TaskInfoHistoryEntity>()
                           .Where(x => DateTime.Parse(x.CreateTime) < date && x.IsUpLoad == "1")
                           .ExecuteCommand();
                    }
                }
            };
        }
    }
}
